package pe.com.upc.edu.rtt.datalayer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

public class Util {

	private static final Log _log = LogFactoryUtil.getLog(Util.class);

	public static String restUtilGet(String uri, String method, String requestPropertyKey, String requestPropertyValue) throws IOException {
		_log.info("uri:" + uri + " method:" + method);
		try {
			URL url = new URL(uri);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
			conn.setRequestProperty(requestPropertyKey, requestPropertyValue);
			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			}
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String output = "", strLineas = "";
			while ((output = br.readLine()) != null) {
				strLineas += output;
			}
			conn.disconnect();
			return strLineas;
		} catch (MalformedURLException e) {
			_log.error("Error de Mal formato de Url ", e);
			throw new MalformedURLException("Error de Mal formato de Url ");
		}
	}

	public static String restUtilPost(String uri, String method, String requestPropertyKey, String requestPropertyValue, String input) throws IOException {
		_log.info("uri:" + uri + " method:" + method);
		try {
			URL url = new URL(uri);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod(method);
			conn.setRequestProperty(requestPropertyKey, requestPropertyValue);
			OutputStream os = conn.getOutputStream();
			os.write(input.getBytes());
			os.flush();
			if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			}
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String output1 = "", strLineas = "";
			while ((output1 = br.readLine()) != null) {
				strLineas += output1;
			}
			conn.disconnect();
			return strLineas;
		} catch (MalformedURLException e) {
			_log.error("Error de Mal formato de Url ", e);
			throw new MalformedURLException("Error de Mal formato de Url ");
		}
	}

}
